package test.model;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import javax.swing.plaf.FileChooserUI;

import demo.ui.ImagePane;

public class UpdateContactFrame extends JFrame{
	
	ImagePane imagePane;
	JButton btnBrowseImage, btnSave;
	JTextField txtName, txtPhoneNumber;
	JTextField txtImagePath;
	File imageFile;
	boolean isChangeImage = false;
	private List<PropertyChangeListener> listener = new ArrayList<PropertyChangeListener>();
	
	ContactItem mItem;
	
	public UpdateContactFrame(){
		super("Add/Update contact");
		initComponent();
	}
	
	public UpdateContactFrame(ContactItem item){
		super("Add/Update contact");
		mItem = item;
		initComponent();
		
		txtName.setText(item.getName());
		txtPhoneNumber.setText(item.getPhone());
		File f = new File(ContactDAO.getPath() + "images/" + item.getImage());
		try {
			BufferedImage image = ImageIO.read(f);
			imagePane.setImage(image);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void addListener(PropertyChangeListener l){
		listener.add(l);
	}
	
	public void removeListener(PropertyChangeListener l){
		listener.remove(l);
	}
	
	private void initComponent(){
		setBounds(10, 10, 400, 200);
		Container c = getContentPane();
		c.setLayout(new GridBagLayout());
		
		GridBagConstraints gbc = new GridBagConstraints();
		imagePane = new ImagePane();
		gbc.anchor = GridBagConstraints.FIRST_LINE_START;
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.gridx = 1;
		gbc.gridy = 0;
		gbc.gridwidth = 4;
		gbc.gridheight = 4;
		c.add(imagePane, gbc);
		
		txtImagePath = new JTextField(10);
		txtImagePath.setEditable(false);
		gbc = new GridBagConstraints();
		gbc.anchor = GridBagConstraints.FIRST_LINE_START;
		gbc.gridx = 0;
		gbc.gridy = 4;
		gbc.gridwidth = 3;
		gbc.gridheight = 1;
		c.add(txtImagePath, gbc);
		
		btnBrowseImage = new JButton("...");
		btnBrowseImage.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser fc = new JFileChooser();
				fc.setAcceptAllFileFilterUsed(false);
				fc.addChoosableFileFilter(new ImageFilter());
				int returnVal = fc.showOpenDialog(UpdateContactFrame.this);
				
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					imageFile = fc.getSelectedFile();
		            
		            try {
						BufferedImage img = ImageIO.read(imageFile);
						imagePane.setImage(img);
						
						String fileName = imageFile.getName();
						txtImagePath.setText(fileName);
						isChangeImage = true;
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		            
		        }
			}
			
		});
		gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.gridx = 3;
		gbc.gridy = 4;
		gbc.gridwidth = 2;
		gbc.gridheight = 1;
		c.add(btnBrowseImage, gbc);
		
		JLabel lb = new JLabel("Fullname ");
		gbc = new GridBagConstraints();
		gbc.anchor = GridBagConstraints.LINE_END;
		gbc.insets = new Insets(0, 5, 0, 3);
		gbc.gridx = 5;
		gbc.gridy = 0;
		gbc.gridwidth = 2;
		gbc.gridheight = 1;
		c.add(lb, gbc);
		txtName = new JTextField(10);
		gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.HORIZONTAL;
		gbc.gridx = 7;
		gbc.gridy = 0;
		gbc.gridwidth = 3;
		gbc.gridheight = 1;
		c.add(txtName, gbc);
		
		lb = new JLabel("Phone number ");
		gbc = new GridBagConstraints();
		gbc.anchor = GridBagConstraints.LINE_END;
		gbc.insets = new Insets(0, 5, 0, 3);
		gbc.gridx = 5;
		gbc.gridy = 1;
		gbc.gridwidth = 2;
		gbc.gridheight = 1;
		c.add(lb, gbc);
		txtPhoneNumber = new JTextField(10);
		gbc = new GridBagConstraints();
		gbc.gridx = 7;
		gbc.gridy = 1;
		gbc.gridwidth = 3;
		gbc.gridheight = 1;
		c.add(txtPhoneNumber, gbc);
		
		btnSave = new JButton("Save");
		btnSave.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if(txtName.getText().length()<=0){
					JOptionPane.showMessageDialog(UpdateContactFrame.this, "Fullname cannot be blank.");
					txtName.requestFocus();
					return;
				}
				
				if(txtPhoneNumber.getText().length()<=0){
					JOptionPane.showMessageDialog(UpdateContactFrame.this, "Phone number cannot be blank.");
					txtPhoneNumber.requestFocus();
					return;
				}
				
				ContactDAO dao = new ContactDAO();
				File f = null;
				String extension = "";
				String newFile = "";
				
				if(mItem != null){
					mItem.setName(txtName.getText());
					mItem.setPhone(txtPhoneNumber.getText());
					
					try{
						//copy image into image_folder
						if(isChangeImage){
							extension = imageFile.getName().substring(imageFile.getName().lastIndexOf("."));
							newFile = ContactDAO.getPath() + "images/" + mItem.getImage();
							dao.copyFileUsingFileStreams(imageFile, f);
						}
						if(dao.updateContact(mItem)){
							for(PropertyChangeListener l: listener){
								l.propertyChange(new PropertyChangeEvent(this, "UpdateItem", null, mItem));
							}
						}
					}catch(Exception ex){
						ex.printStackTrace();
					}
					return;
				}
				
				ContactItem item = new ContactItem();
				item.setName(txtName.getText());
				item.setPhone(txtPhoneNumber.getText());
				
				SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
				
				newFile = ContactDAO.getPath() + "images/img" + sdf.format(new Date()) + extension;
				System.out.println(newFile);
				f = new File(newFile);
				item.setImage("img" + sdf.format(new Date()) + extension);
				try{
					//copy image into image_folder
					dao.copyFileUsingFileStreams(imageFile, f);
					if(dao.addContact(item)){
						for(PropertyChangeListener l: listener){
							l.propertyChange(new PropertyChangeEvent(this, "NewItem", null, item));
						}
					}
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
			
		});

		gbc = new GridBagConstraints();
		gbc.gridx = 7;
		gbc.gridy = 3;
		gbc.gridwidth = 4;
		gbc.gridheight = 1;
		c.add(btnSave, gbc);
		
		
		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent we){
				listener.clear();
			}
		});
	}
}

class ImageFilter extends FileFilter {
	
	public final static String jpeg = "jpeg";
    public final static String jpg = "jpg";
    public final static String gif = "gif";
    public final static String tiff = "tiff";
    public final static String tif = "tif";
    public final static String png = "png";

    //Accept all directories and all gif, jpg, tiff, or png files.
    public boolean accept(File f) {
        if (f.isDirectory()) {
            return true;
        }

        String extension = getExtension(f);
        if (extension != null) {
            if (extension.equals(tiff) ||
                extension.equals(tif) ||
                extension.equals(gif) ||
                extension.equals(jpeg) ||
                extension.equals(jpg) ||
                extension.equals(png)) {
                    return true;
            } else {
                return false;
            }
        }

        return false;
    }

    //The description of this filter
    public String getDescription() {
        return "Just Images";
    }
    
    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }
}